package ru.ifmo.ct.network.brafs.file;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Alex Vikharev vikharev@yandex-team.ru
 *         created 20.04.12
 */
public class InMemoryFileHolder implements FileHolder {
    private final Map<SegmentId, byte[]> segments = new HashMap<>();

    @Override
    public byte[] get(final String fileId, final long segmentId) {
        return segments.get(new SegmentId(fileId, segmentId));
    }

    @Override
    public int hash(final String fileId, final long segmentId) {
        final byte[] bytes = segments.get(new SegmentId(fileId, segmentId));
        if (bytes == null) {
            return 0;
        }
        final int hash = Arrays.hashCode(bytes);
        return hash == 0 ? 1 : hash;
    }

    @Override
    public void put(final String fileId, final long segmentId, final byte[] data) {
        segments.put(new SegmentId(fileId, segmentId), data);
    }

    @Override
    public void delete(final String fileId, final long segmentId) {
        segments.remove(new SegmentId(fileId, segmentId));
    }

}
